'use strict';

const Service = require('egg').Service;

class TaskService extends Service {
  async list(state) {
    const { app } = this;
    const QUERY_STR = 'id,task,time,complete,state';
    let sql;
    if (+state === 0) {
      sql = `select ${QUERY_STR} from task`;
    } else {

      sql = `select ${QUERY_STR} from task where state =${state}`;
    }
    try {
      const result = await app.mysql.query(sql);
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  async add(params) {
    const { app } = this;
    try {
      const result = await app.mysql.insert('task', params);
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  async delete(id) {
    const { app } = this;
    try {
      const result = await app.mysql.delete('task', { id });
      return result;
    } catch (error) {
      return null;
    }
  }
  async update(params) {
    const { app } = this;
    try {
      const result = await app.mysql.update('task', { ...params }, { id: params.id });
      return result;
    } catch (error) {
      return null;
    }
  }
  async edit(id) {
    const { app } = this;
    const QUERY_STR = 'id,task,time,complete,state';
    const sql = `select ${QUERY_STR} from task where id =${id}`;
    try {
      const result = await app.mysql.query(sql);
      return result;
    } catch (error) {
      return null;
    }
  }
}

module.exports = TaskService;
